package com.mmc.delay.api.impl;

import com.mmc.delay.api.DelayFacade;
import com.mmc.delay.api.JobHandle;
import com.mmc.delay.api.Producer;
import com.mmc.delay.bean.JobParam;
import com.mmc.delay.config.DelayCoreConfig;
import com.mmc.delay.config.TopicConfig;
import com.mmc.delay.exception.DelayException;
import com.mmc.delay.timer.DelayMoveToReadyTimer;
import com.mmc.delay.timer.ReadyQueueTimer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DelayProducer implements Producer {

    private final DelayFacade delayFacade;

    private static final ExecutorService executorService = Executors.newSingleThreadExecutor();

    private static final Logger logger = LoggerFactory.getLogger(DelayProducer.class);


    private DelayProducer(){
        delayFacade=null;
        throw new DelayException("非法构造");
    }


    public DelayProducer(RedisTemplate redisTemplate) {
        this.delayFacade = new DelayFacadeImpl(redisTemplate);
        init();
    }

    @Override
    public void setTopicConfig(String topic, TopicConfig topicConfig) {
        DelayCoreConfig.setTopicConfig(topic, topicConfig);
    }


    @Override
    public void setTimerIp(String timerIp) {
        DelayCoreConfig.setTimerIp(timerIp);
    }

    @Override
    public void setJobHandle(String topic, JobHandle jobHandle) {
        if(topic==null){
            throw new DelayException("topic不能为空");
        }
        if(jobHandle==null){
            throw new DelayException("jobHandle不能为空");
        }
       DelayCoreConfig.addJobHandle(topic, jobHandle);
    }

    @Override
    public boolean asyncPutMessage(final JobParam jobParam) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                delayFacade.addJob(jobParam);
            }
        });
        return true;
    }

    @Override
    public boolean syncPutMessage(JobParam jobParam) {
        return delayFacade.addJob(jobParam);
    }

    public void init() {
        registerDestroy();
    }

    /**
     * 优雅停机
     */
    private void registerDestroy() {
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                logger.info("触发优雅停机");
                close();

            }
        }));
    }



    @Override
    public void close() {
        executorService.shutdown();
        DelayMoveToReadyTimer.DELAY_REMOVE_THREAD_POOL_EXECUTOR.shutdown();
        ReadyQueueTimer.JOB_HANDLE_THREAD_POOL_EXECUTOR.shutdown();
        ReadyQueueTimer.READY_CONSUME_THREAD_POOL_EXECUTOR.shutdown();
    }

}
